from fastapi import APIRouter
from fastapi import Form
import psycopg2
from fastapi import Request
from pydantic import BaseModel
from typing import Union
from fastapi.templating import Jinja2Templates
from pathlib import Path
import os
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi import File,UploadFile
from typing import Union,List
import time
from fastapi.staticfiles import StaticFiles
from fastapi import WebSocket
from fastapi import WebSocketDisconnect
import json
import asyncio
from fastapi.responses import JSONResponse





# fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]

app_request = APIRouter(
    tags=['客户端模块'],
)

class UserL(BaseModel):
    username: str
    password: str

@app_request.post('/login')
def login(user: UserL):
    with psycopg2.connect("dbname=Web user=postgres password=52cy1314") as conn:
        with conn.cursor() as cursor:
            cursor.execute("SELECT * FROM login WHERE username=%s AND password=%s", (user.username, user.password))
            result = cursor.fetchall()
            if result:
                # Return a success response with the username
                return {"code": 200, "message": "登录成功", "username": user.username}
            else:
                # Return an error response with a message
                return {"code": 400, "message": "账号或密码错误"}
            

@app_request.post("/register")
async def register(user:UserL):
    try:
        with psycopg2.connect("dbname=Web user=postgres password=52cy1314") as conn:
            with conn.cursor() as cursor:
                cursor.execute("INSERT INTO login VALUES (%s, %s)", (user.username, user.password))
                conn.commit()
                return {"code": 200, "message": "注册成功", "username": user.username}
    except Exception as e:
        return {"code": 500, "message": f"注册失败：{str(e)}"}



